import '../../domain/repositories/auth_repository.dart';
import '../../data/models/user_model.dart';
import '../../data/models/api_response.dart';

/// 认证用例
class AuthUseCases {
  final AuthRepository _repository;

  AuthUseCases(this._repository);

  /// 用户登录用例
  Future<LoginResult> login({
    required String username,
    required String password,
    bool rememberMe = false,
  }) async {
    try {
      if (username.trim().isEmpty) {
        return LoginResult.failure('用户名不能为空');
      }

      if (password.trim().isEmpty) {
        return LoginResult.failure('密码不能为空');
      }

      final request = LoginRequest(
        username: username.trim(),
        password: password,
        rememberMe: rememberMe,
      );

      final response = await _repository.login(request);

      return LoginResult.success(response);
    } on BusinessException catch (e) {
      return LoginResult.failure(e.message);
    } on NetworkException catch (e) {
      return LoginResult.failure(e.message);
    } catch (e) {
      print('登录用例中发生未处理的异常: $e');
      return LoginResult.failure('登录失败：${e.toString()}');
    }
  }

  /// 用户登出用例
  Future<LogoutResult> logout({bool clearLocalData = false}) async {
    try {
      await _repository.logout(clearLocalData: clearLocalData);
      return LogoutResult.success();
    } catch (e) {
      return LogoutResult.failure('登出失败：${e.toString()}');
    }
  }

  /// 检查登录状态用例
  Future<bool> isLoggedIn() async {
    try {
      return await _repository.isLoggedIn();
    } catch (e) {
      return false;
    }
  }

  /// 获取当前用户信息用例
  Future<UserResult> getCurrentUser({bool forceUpdate = false}) async {
    try {
      final userInfo =
          await _repository.getCurrentUser(forceUpdate: forceUpdate);
      return UserResult.success(userInfo);
    } on BusinessException catch (e) {
      return UserResult.failure(e.message);
    } on NetworkException catch (e) {
      return UserResult.failure(e.message);
    } catch (e) {
      return UserResult.failure('获取用户信息失败：${e.toString()}');
    }
  }

  /// 获取本地存储的用户信息用例
  Future<UserInfo?> getStoredUserInfo() async {
    try {
      return await _repository.getStoredUserInfo();
    } catch (e) {
      return null;
    }
  }

  /// 刷新Token用例
  Future<RefreshTokenResult> refreshToken() async {
    try {
      final response = await _repository.refreshToken();
      return RefreshTokenResult.success(response);
    } on BusinessException catch (e) {
      return RefreshTokenResult.failure(e.message);
    } on NetworkException catch (e) {
      return RefreshTokenResult.failure(e.message);
    } catch (e) {
      return RefreshTokenResult.failure('Token刷新失败：${e.toString()}');
    }
  }

  /// 验证Token用例
  Future<bool> validateToken() async {
    try {
      return await _repository.validateToken();
    } catch (e) {
      return false;
    }
  }

  /// 保存用户信息到本地存储用例
  Future<void> saveUserInfo(UserInfo userInfo) async {
    try {
      await _repository.saveUserInfo(userInfo);
    } catch (e) {
      // 静默处理错误
      rethrow;
    }
  }

  /// 清除认证数据用例
  Future<void> clearAuthData() async {
    try {
      await _repository.clearAuthData();
    } catch (e) {
      // 静默处理错误
    }
  }
}

/// 登录结果
class LoginResult {
  final bool isSuccess;
  final String? errorMessage;
  final LoginResponse? data;

  LoginResult._({
    required this.isSuccess,
    this.errorMessage,
    this.data,
  });

  factory LoginResult.success(LoginResponse data) {
    return LoginResult._(
      isSuccess: true,
      data: data,
    );
  }

  factory LoginResult.failure(String message) {
    return LoginResult._(
      isSuccess: false,
      errorMessage: message,
    );
  }
}

/// 登出结果
class LogoutResult {
  final bool isSuccess;
  final String? errorMessage;

  LogoutResult._({
    required this.isSuccess,
    this.errorMessage,
  });

  factory LogoutResult.success() {
    return LogoutResult._(isSuccess: true);
  }

  factory LogoutResult.failure(String message) {
    return LogoutResult._(
      isSuccess: false,
      errorMessage: message,
    );
  }
}

/// 用户信息结果
class UserResult {
  final bool isSuccess;
  final String? errorMessage;
  final UserInfo? data;

  UserResult._({
    required this.isSuccess,
    this.errorMessage,
    this.data,
  });

  factory UserResult.success(UserInfo data) {
    return UserResult._(
      isSuccess: true,
      data: data,
    );
  }

  factory UserResult.failure(String message) {
    return UserResult._(
      isSuccess: false,
      errorMessage: message,
    );
  }
}

/// Token刷新结果
class RefreshTokenResult {
  final bool isSuccess;
  final String? errorMessage;
  final LoginResponse? data;

  RefreshTokenResult._({
    required this.isSuccess,
    this.errorMessage,
    this.data,
  });

  factory RefreshTokenResult.success(LoginResponse data) {
    return RefreshTokenResult._(
      isSuccess: true,
      data: data,
    );
  }

  factory RefreshTokenResult.failure(String message) {
    return RefreshTokenResult._(
      isSuccess: false,
      errorMessage: message,
    );
  }
}
